package cn.xw.helloWorld;

import cn.xw.utils.ChannelUtil;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author AnHui OuYang
 * @version 1.0
 * created at 2023-04-11 22:14
 * 消费者（消费任务）
 */
public class Consumer {

    //通过日志管理器获取Logger对象
    static Logger logger = LogManager.getLogger(Producer.class);
    //简单队列名称
    public static final String QUEUE_NAME = "helloWorldQueue";

    public static void main(String[] args) throws IOException {
        //通过工具类获取一个信道
        Channel channel = ChannelUtil.getChannel();
        logger.info("消费者开始监听队列消息....");
        //推送的消息如何进行消费的接口回调
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                logger.info("获取队列信息{}", new String(message.getBody(), StandardCharsets.UTF_8));
            }
        };
        //取消消费的一个回调接口 如在消费的时候队列被删除掉了
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
                logger.info("监听的队列出现异常；可能队列被删除！{}", consumerTag);
            }
        };
        //消费者消费消息
        //参数一：消费哪个队列
        //参数二：消费成功之后是否要自动应答 true 代表自动应答 false 手动应答
        //参数三：接受队列消息的回调接口
        //参数四：取消消费的回调接口
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);
    }
}